class Solution {

    //存储图的出边数组
    private List<List<Integer>> edges;
    //每个元素的入度
    private int[] inDeg;

    public int[] findOrder(int numCourses, int[][] prerequisites) {
        edges = new ArrayList<>();
        inDeg = new int[numCourses];
        //初始化出边数组和入度数组
        for(int n=0; n<numCourses; n++){
            edges.add(new ArrayList<Integer>());
            inDeg[n]=0;
        }
        for(int[] pre : prerequisites){
            int x = pre[0];
            int y = pre[1];
            edges.get(y).add(x);
            inDeg[x]++;
        }
        //排序队列
        Queue<Integer> queue = new LinkedList<>();
        for(int i=0; i<numCourses; i++){
            if(inDeg[i]==0)queue.offer(i);
        }
        List<Integer> course = new ArrayList<>();
        while(queue.peek()!=null){
            int x = queue.poll();
            course.add(x);
            for(int y : edges.get(x)){
                inDeg[y]--;
                if(inDeg[y]==0)queue.offer(y);
            }
        }
        if(course.size()==numCourses) return course.stream().mapToInt(Integer::intValue).toArray();
        return new int[]{};
    }
}